package com.pengtu.utils;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * String Utility Class This is used to encode passwords programmatically
 * 
 * <p>
 * <a h ref="StringUtil.java.html"><i>View Source</i></a>
 * </p>
 * 
 * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
 */
public class StringUtils {
	// ~ Static fields/initializers
	// =============================================

	private final static Log log = LogFactory.getLog(StringUtils.class);
	private final static Map<String, Object> colorByid = new HashMap<String, Object>();

	// ~ Methods
	// ================================================================

	/**
	 * Encode a string using algorithm specified in web.xml and return the
	 * resulting encrypted password. If exception, the plain credentials string
	 * is returned
	 * 
	 * @param password
	 *            Password or other credentials to use in authenticating this
	 *            username
	 * @param algorithm
	 *            Algorithm used to do the digest
	 * 
	 * @return encypted password based on the algorithm.
	 */
	public static String encodePassword(String password, String algorithm) {
		byte[] unencodedPassword = password.getBytes();

		MessageDigest md = null;

		try {
			// first create an instance, given the provider
			md = MessageDigest.getInstance(algorithm);
		} catch (Exception e) {
			log.error("Exception: " + e);

			return password;
		}

		md.reset();

		// call the update method one or more times
		// (useful when you don't know the size of your data, eg. stream)
		md.update(unencodedPassword);

		// now calculate the hash
		byte[] encodedPassword = md.digest();

		StringBuffer buf = new StringBuffer();

		for (int i = 0; i < encodedPassword.length; i++) {
			if ((encodedPassword[i] & 0xff) < 0x10) {
				buf.append("0");
			}

			buf.append(Long.toString(encodedPassword[i] & 0xff, 16));
		}

		return buf.toString();
	}

	/**
	 * 判断字符串是email
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isEmail(String email) {
		Pattern pattern = Pattern
				.compile("^/w+([-.]/w+)*@/w+([-]/w+)*/.(/w+([-]/w+)*/.)*[a-z]{2,3}$");
		Matcher matcher = pattern.matcher(email);
		if (matcher.matches()) {
			return true;
		}
		return false;

	}

	/**
	 * 判断字符串是否有中文
	 * 
	 * @param str
	 * @return
	 */
	public static boolean hasChinese(String str) {
		if (str == null) {
			return false;
		}
		if (str.getBytes().length != str.length()) {
			return true;
		}
		return false;

	}

	/**
	 * 字符串分割 默认按照";" 分割
	 * 
	 * @param selItem
	 * @return
	 */
	public static String[] getItemsForSplit(String selItem) {
		return getItemsForSplit(selItem, ";");
	}

	/**
	 * 字符串分割
	 * 
	 * @param selItem
	 * @return
	 */
	public static String[] getItemsForSplit(String selItem, String split) {
		if (selItem == null) {
			return new String[0];
		}
		return selItem.split(split);
	}

	/**
	 * 格式化数字，若为 null 返回 ""，否则返回其数值
	 * 
	 * @author 谢庚才
	 * @param number
	 * @return
	 */
	public static String formatNumber(Number number) {
		if (number != null) {
			return number + "";
		} else {
			return "";
		}
	}

	/**
	 * 格式化桩号 将Double类型的桩号 转化为 形如K999+333类型的桩号写法 犹如0.0转化为 K0+0 犹如333转化为 K333+0
	 * 犹如3.33 转化成3K330米
	 * 
	 * @param pegNum
	 * @return
	 */
	public static String formatPegNum(Number pegNum) {
		if (pegNum == null) {
			return "";
		}

		Double doubleValue = new Double(pegNum.doubleValue());
		doubleValue = doubleValue * 1000;

		Double kilo = (doubleValue / 1000);
		int kiloPart = kilo.intValue();
		Double meterPart = doubleValue - kiloPart * 1000;
		return "K" + kiloPart + "+" + meterPart.intValue();

	}

	/**
	 * 格式化桩号 将Double类型的桩号 转化为 形如K999+333类型的桩号写法 犹如0.0转化为 K0+0 犹如333转化为 K333+0
	 * 
	 * @param pegNum
	 * @return
	 */
	public static String formatPegNum(String pegNum) {
		if (pegNum == null) {
			return "";
		}
		return formatPegNum(Double.parseDouble(pegNum));
	}

	/** 随机获取颜色样式 */
	public static String randomColor() {
		String t = "#";
		String str = "0123456789abcdef";
		for (int j = 0; j < 6; j++) {
			t = t + str.charAt((int) (Math.random() * str.length()));
		}
		return t;
	}

	/** 根据id获取对应的颜色 */
	public static String colorMapById(String id) {
		String color = null;
		if (colorByid.containsKey(id)) {
			color = (String) colorByid.get(id);
		} else {
			color = randomColor();
			colorByid.put(id, color);
		}
		return color;
	}

	/**
	 * 根据字符串找到 < >之间的字符串
	 * 
	 * @param str
	 * @return list
	 */
	public static List<String> findString(String str) {
		// String str
		// ="管理员<admin>;陈惠芬<chenhf>;康从宇<kangcy>;黄惠初<huanghc>;周小浪<zhouxl>";
		List<String> list = new ArrayList<String>();
		if (str == null) {
			return list;
		}
		for (int i = 0; i < str.length(); i++) {

			int start = str.indexOf("<");
			int end = str.indexOf(">");
			if (start != -1 && end != -1) {
				String findStr = str.substring(start + 1, end);
				list.add(findStr);
				// 如果找到 findStr 后 ,findStr还有字符
				if (!str.substring(start + 1).equals(
						str.substring(start + 1, end + 1))) {
					str = str.substring(end + 1);
				} else {
					break;
				}
			} else {
				break;
			}

		}

		return list;
	}

	/**
	 * 根据字符串找到 < >之间的字符串
	 * getString:
	 * 适用:
	 * @param str
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	public static String getString(String str) {
		if (str == null || str.equals("")) {
			return null;
		}
		int start = str.indexOf("<");
		int end = str.indexOf(">");
		if (start != -1 && end != -1) {
			String findStr = str.substring(start + 1, end);
			// 如果找到 findStr 后 ,findStr还有字符
			if (!str.substring(start + 1).equals(
					str.substring(start + 1, end + 1))) {
				str = str.substring(end + 1);
			}
			return findStr;
		}
		return null;
	}
	
	/**   
     * 获得一个UUID   
     * @return String UUID   
     */    
    public static String getUUID(){    
        String s = UUID.randomUUID().toString();    
        return s.substring(0,8)+s.substring(9,13)+s.substring(14,18)+s.substring(19,23)+s.substring(24);    
    }    
    /**   
     * 获得指定数目的UUID   
     * @param number int 需要获得的UUID数量   
     * @return String[] UUID数组   
     */    
    public static String[] getUUID(int number){    
        if(number < 1){    
            return null;    
        }    
        String[] ss = new String[number];    
        for(int i=0;i<number;i++){    
            ss[i] = getUUID();    
        }    
        return ss;    
    }
    
    /**
     * 将字符串按指定符号分割为数组
     * resolveString:
     * 适用:
     * @return 
     * @exception 
     * @since  1.0.0
     */
    public static String[] resolveString(String value , String  mark){
    	String [] strarray  = null;
    	 if(value != null) {
    		strarray = value.split(mark);
    	 }
    	return  strarray;
    }
    
    /**
     * 将数组拼接为字符串
     * appendString:
     * 适用:
     * @param array
     * @return 
     * @exception 
     * @since  1.0.0
     */
    public static String appendString(String [] array ){
    	StringBuffer appenStr = new StringBuffer();
    	for (int i = 0;i<array.length;i++) {
			if(i==array.length-1){
				appenStr.append(array[i]);
			}else{
				appenStr.append(array[i]+",");
			}
		}
    	return appenStr.toString();
    }
    
    /**
     * 
     * changeHTML:
     * 适用:转化html代码
     * @param value
     * @return 
     * @exception 
     * @since  1.0.0
     */
    public static String changeHTML(String value){
		value=value.replace("&","&amp;");
		value=value.replace(" ","&nbsp;");
		value=value.replace("<","&lt;");
		value=value.replace(">","&gt;");
		value=value.replace("\r\n","<br>");
		return value;
	}
}
